<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '项目信息' : '新建项目信息'"
    :toolbar-attrs="{
      buttons: [
        'back',
        {
          save: isDraft || flowContext.isStartNode,
          submit: hasBtn('submit'),
          withdraw: flowContext.canWithdraw,
          reject: flowContext.canReject,
          finish: hasBtn('finish')
        }
      ]
    }"
    :toolbar-listeners="{
      save: () => saveAndStart({ title: `${userName}的项目信息申请` }),
      submit: submitAudit,
      finish: () => submitAudit({}),
      withdraw: () => withdrawAudit(),
      reject: () => reject()
    }">
    <template #toolbar-right> </template>
    <FormHolder ref="form" label-width="150px" :disabled="isFinish" :model="entity">
      <FormItemGroup block-title="基本信息">
        <FormInput v-model="entity.createBy" prop="projectName" label="创建人" disabled required />
        <FormInput v-model="entity.deptFullName" prop="projectName" label="创建单位" disabled required />
        <FormInput v-model="entity.projectName" prop="projectName" label="项目名称" required />
        <FormInput v-model="entity.projectNo" prop="projectNo" label="项目编号" required disabled />
        <FormInputUser :id.sync="entity.masterId" :name.sync="entity.masterName" prop="masterName" label="负责人姓名" required @input="setMaster" />
        <FormInput v-model="entity.masterUnitName" prop="masterUnitName" label="负责人单位" required readonly disabled />
        <FormDatePicker
          v-model="entity.beginDateTime"
          prop="beginDateTime"
          :start.sync="entity.beginDateTime"
          :end.sync="entity.endDateTime"
          date-range
          label="起止时间"
          required />
        <FormInputNumber v-model="entity.funds" prop="funds" label="经费" required><template #append> 万元 </template></FormInputNumber>
        <FormInputNumber
          :value="entity.topics.reduce((acc, cur) => acc + Number(cur.funds), 0)"
          label="局实际承担经费"
          :placeholder="null"
          disabled>
          <template #append> 万元 </template>
        </FormInputNumber>
        <FormSelect v-model="entity.projectStatus" prop="projectStatus" label="状态" required dict-type="project_status" />
        <FormSelect v-model="entity.projectType" prop="projectType" label="项目类型" required dict-type="project_type" />
        <FormInput v-model="entity.manageOrg" prop="manageOrg" label="项目管理专业机构" />
        <FormInputDepartment
          :id.sync="entity.departmentId"
          :name.sync="entity.departmentName"
          prop="departmentName"
          label="所属部门名称"
          required
          @input="setDepartment" />
        <FormTextarea v-model="entity.summary" prop="summary" label="摘要" max-length="1000" required />
        <FormTextarea v-model="entity.remark" prop="remark" label="备注" max-length="3000" />
      </FormItemGroup>
      <FormItemGroup enabled block-title="项目课题">
        <FormTablePlus
          v-model="entity.topics"
          :toolbar-menus="isDraft || isProcessing ? ['add', 'delete'] : []"
          label="课题"
          hide-label
          :selection="isDraft || isProcessing"
          prefix-pick
          label-width="0"
          prop="topics"
          :columns="topicColumns"
          @add-row="addTopic()">
          <template v-if="isFinish" #toolbar-right>
            <ElButton size="mini" type="primary" @click="isTopicUpdateRecordsDialogVisible = true">变更记录</ElButton>
            <ElButton
              size="mini"
              type="primary"
              @click="$router.push(`/tech-project/project-manage/topic/update/ProjectTopicUpdateForm/-1?projectId=${entity.id}`)">
              课题变更
            </ElButton>
          </template>
          <template #handle="{ remove }">
            <TableColumn #default="{ row, $index }" label="操作" align="center">
              <template v-if="isDraft || isProcessing">
                <ElButton size="mini" type="text" @click="addTopic($index)">添加</ElButton>
                <ElButton size="mini" type="text" @click="editTopic(row, $index)">编辑</ElButton>
                <ElButton size="mini" type="text" @click="remove">删除</ElButton>
              </template>
              <ElButton v-if="isFinish" size="mini" type="text" @click="viewTopic(row, $index)">查看</ElButton>
            </TableColumn>
          </template>
        </FormTablePlus>
      </FormItemGroup>
      <FormItemGroup enabled :gutter="0" block-title="项目成员">
        <FormTablePlus
          v-model="entity.members"
          :toolbar-menus="isDraft || isProcessing ? ['add', 'delete'] : []"
          label="成员"
          hide-label
          :selection="isDraft || isProcessing"
          prefix-pick
          label-width="0"
          prop="members"
          :columns="memberColumns"
          @add-row="addMember()">
          <template v-if="isFinish" #toolbar-right>
            <ElButton size="mini" type="primary" @click="isMemberUpdateRecordsDialogVisible = true">变更记录</ElButton>
            <ElButton
              size="mini"
              type="primary"
              @click="$router.push(`/tech-project/project-manage/member/update/ProjectMemberUpdateForm/-1?projectId=${entity.id}`)">
              成员变更
            </ElButton>
          </template>
          <template #handle="{ remove }">
            <TableColumn #default="{ row, $index }" label="操作" align="center">
              <template v-if="isDraft || isProcessing">
                <ElButton size="mini" type="text" @click="addMember($index)">添加</ElButton>
                <ElButton size="mini" type="text" @click="editMember(row, $index)">编辑</ElButton>
                <ElButton size="mini" type="text" @click="remove">删除</ElButton>
              </template>
              <ElButton v-if="isFinish" size="mini" type="text" @click="viewMember(row, $index)">查看</ElButton>
            </TableColumn>
          </template>
        </FormTablePlus>
      </FormItemGroup>
      <FormItemGroup enabled block-title="研究阶段">
        <FormTablePlus
          v-model="entity.stages"
          :toolbar-menus="isDraft || isProcessing ? ['add', 'delete'] : []"
          label="阶段"
          hide-label
          :selection="isDraft || isProcessing"
          prefix-pick
          label-width="0"
          prop="stages"
          :columns="stageColumns"
          @add-row="addStage()">
          <template v-if="isFinish" #toolbar-right>
            <ElButton size="mini" type="primary" @click="isStageUpdateRecordsDialogVisible = true">变更记录</ElButton>
            <ElButton
              size="mini"
              type="primary"
              @click="$router.push(`/tech-project/project-manage/stage/update/ProjectStageUpdateForm/-1?projectId=${entity.id}`)">
              阶段变更
            </ElButton>
          </template>
          <template #handle="{ remove }">
            <TableColumn #default="{ row, $index }" label="操作" align="center">
              <template v-if="isDraft || isProcessing">
                <ElButton size="mini" type="text" @click="addStage($index)">添加</ElButton>
                <ElButton size="mini" type="text" @click="editStage(row, $index)">编辑</ElButton>
                <ElButton size="mini" type="text" @click="remove">删除</ElButton>
              </template>
              <ElButton v-if="isFinish" size="mini" type="text" @click="viewStage(row, $index)">查看</ElButton>
            </TableColumn>
          </template>
        </FormTablePlus>
      </FormItemGroup>
    </FormHolder>
    <TopicEditDialog
      v-if="isTopicDialogVisible"
      :disabled="isView"
      :visible.sync="isTopicDialogVisible"
      :value="topic"
      @close="topic = null"
      @confirm="onTopicConfirm" />
    <MemberEditDialog
      v-if="isMemberDialogVisible"
      :disabled="isView"
      :visible.sync="isMemberDialogVisible"
      :value="member"
      @close="member = null"
      @confirm="onMemberConfirm" />
    <StageEditDialog
      v-if="isStageDialogVisible"
      :disabled="isView"
      :visible.sync="isStageDialogVisible"
      :value="stage"
      @close="stage = null"
      @confirm="onStageConfirm" />
    <TopicUpdateRecordsDialog v-if="isTopicUpdateRecordsDialogVisible" :project-id="id" :visible.sync="isTopicUpdateRecordsDialogVisible" />
    <MemberUpdateRecordsDialog v-if="isMemberUpdateRecordsDialogVisible" :project-id="id" :visible.sync="isMemberUpdateRecordsDialogVisible" />
    <StageUpdateRecordsDialog v-if="isStageUpdateRecordsDialogVisible" :project-id="id" :visible.sync="isStageUpdateRecordsDialogVisible" />
  </FormView>
</template>

<script>
  import { save, create, load, update } from './api'
  import flowForm from '@/vue/mixin/flow-form'
  import MemberEditDialog from '@/module/tech-project/project-manage/member/MemberEditDialog.vue'
  import StageEditDialog from '@/module/tech-project/project-manage/stage/StageEditDialog.vue'
  import TopicEditDialog from '@/module/tech-project/project-manage/topic/TopicEditDialog.vue'
  import { memberColumns, stageColumns, topicColumns } from '@/module/tech-project/project-manage'
  import StageUpdateRecordsDialog from '@/module/tech-project/project-manage/stage/update/StageUpdateRecordsDialog.vue'
  import TopicUpdateRecordsDialog from '@/module/tech-project/project-manage/topic/update/TopicUpdateRecordsDialog.vue'
  import MemberUpdateRecordsDialog from '@/module/tech-project/project-manage/member/update/MemberUpdateRecordsDialog.vue'

  export default {
    name: 'FyProjectInfoForm',
    components: {
      MemberUpdateRecordsDialog,
      TopicUpdateRecordsDialog,
      StageUpdateRecordsDialog,
      TopicEditDialog,
      StageEditDialog,
      MemberEditDialog
    },
    docType: 'WF_PROJECT_INFO',
    relativeViewId: 'ProjectInformationView',
    bus: {
      reloadTableView(viewId, params) {
        if (
          ['ProjectTopicUpdateView', 'ProjectMemberUpdateView', 'ProjectStageUpdateView'].includes(viewId) &&
          params &&
          params.status === 2 &&
          params.projectId === this.entity.id &&
          this.entity.status === 2
        ) {
          this.initForm()
        }
      }
    },
    mixins: [flowForm],
    data() {
      return {
        isTopicDialogVisible: false,
        isMemberDialogVisible: false,
        isStageDialogVisible: false,
        isTopicUpdateRecordsDialogVisible: false,
        isMemberUpdateRecordsDialogVisible: false,
        isStageUpdateRecordsDialogVisible: false,
        entity: {
          id: null,
          unid: null,
          createTime: null,
          createBy: null,
          createId: null,
          deptId: null,
          deptFullName: null,
          updateTime: null,
          updateId: null,
          updateBy: null,
          tenantId: null,
          delFlag: null,
          projectNo: null,
          masterId: null,
          masterName: null,
          masterUnitId: null,
          masterUnitName: null,
          masterUnitFullName: null,
          beginDateTime: null,
          endDateTime: null,
          funds: null,
          projectStatus: null,
          projectType: null,
          status: null,
          manageOrg: null,
          departmentId: null,
          departmentName: null,
          departmentFullName: null,
          departmentFullCode: null,
          summary: null,
          remark: null,
          delegateId: null,
          delegateName: null,
          members: [],
          topics: [],
          stages: []
        },
        memberColumns,
        topicColumns,
        stageColumns,
        topic: null,
        member: null,
        stage: null,
        isView: false,
        editIndex: null
      }
    },
    methods: {
      create,
      load,
      save,
      update,
      async initEntity(id) {
        const entity = await this.loadEntity(id)
        entity.books = entity.books || []
        this.entity = entity
      },
      addTopic(index) {
        this.editIndex = index
        this.isTopicDialogVisible = true
      },
      viewTopic(row) {
        this.topic = row
        this.isView = true
        this.isTopicDialogVisible = true
      },
      editTopic(row, index) {
        this.editIndex = index
        this.topic = row
        this.isTopicDialogVisible = true
      },
      onTopicConfirm(topic) {
        if (this.editIndex !== null && this.topic) {
          this.$set(this.entity.topics, this.editIndex, topic)
          this.editIndex = null
          this.topic = null
        } else if (this.editIndex !== null) {
          this.entity.topics.splice(this.editIndex + 1, 0, topic)
        } else {
          this.entity.topics.push(topic)
        }
      },
      addMember(index) {
        this.editIndex = index
        this.isMemberDialogVisible = true
      },
      viewMember(row) {
        this.member = row
        this.isView = true
        this.isMemberDialogVisible = true
      },
      editMember(row, index) {
        this.editIndex = index
        this.member = row
        this.isMemberDialogVisible = true
      },
      onMemberConfirm(member) {
        if (this.editIndex !== null && this.member) {
          this.$set(this.entity.members, this.editIndex, member)
          this.editIndex = null
          this.member = null
        } else if (this.editIndex !== null) {
          this.entity.members.splice(this.editIndex + 1, 0, member)
        } else {
          this.entity.members.push(member)
        }
      },
      addStage(index) {
        this.editIndex = index
        this.isStageDialogVisible = true
      },
      viewStage(row) {
        this.stage = row
        this.isView = true
        this.isStageDialogVisible = true
      },
      editStage(row, index) {
        this.editIndex = index
        this.stage = row
        this.isStageDialogVisible = true
      },
      onStageConfirm(stage) {
        if (this.editIndex !== null && this.stage) {
          this.$set(this.entity.stages, this.editIndex, stage)
          this.editIndex = null
          this.stage = null
        } else if (this.editIndex !== null) {
          this.entity.stages.splice(this.editIndex + 1, 0, stage)
        } else {
          this.entity.stages.push(stage)
        }
      },
      setMaster([{ deptId, deptName, deptFullname }]) {
        this.entity.masterUnitId = deptId
        this.entity.masterUnitName = deptName
        this.entity.masterUnitFullName = deptFullname
      },
      setDepartment([{ fullcode, fullname }]) {
        this.entity.departmentFullName = fullname
        this.entity.departmentFullCode = fullcode
      }
    }
  }
</script>
